package com.react.bluetoothprinter;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.example.tscdll.TSCActivity;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Set;
import java.util.Vector;

import static com.react.bluetoothprinter.RNBluetoothPackage.TAG;

public class RNBluetoothModule extends ReactContextBaseJavaModule {

    private BluetoothAdapter mBtAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;
    private ReactContext mReactContext;
    TSCActivity printUtils = new TSCActivity();
    ConnectPrinter cPrinter = new ConnectPrinter();

    public RNBluetoothModule(ReactApplicationContext reactContext) {
        super(reactContext);
        mReactContext = reactContext;

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        mReactContext.registerReceiver(mReceiver, filter);

        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mReactContext.registerReceiver(mReceiver, filter);
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    @Override
    public String getName() {
        return "RNBluetoothModule";
    }


    @ReactMethod
    public void scanForPeripherals() {


        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

        // If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                Log.i(TAG, device.getName());
                mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        } else {
            String noDevices = "无配对";
            mPairedDevicesArrayAdapter.add(noDevices);
        }

        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }
        mBtAdapter.startDiscovery();

    }

    @ReactMethod
    public void labelPrint(WritableMap data) {
        String logisticsName = data.getString("logisticsName");
        String userName = data.getString("userName");
        String mobile = data.getString("mobile");
        String address = data.getString("address");
        String collection = data.getString("collection");
        String currentCount = data.getString("currentCount");
        String totalCount = data.getString("totalCount");
        String number = data.getString("number");
        String account = data.getString("account");
        String storeMobile = data.getString("storeMobile");
        String qrImage = data.getString("qrImage");

        LabelCommand command = new LabelCommand();
        command.addSize(80, 60);
        command.addGap(2);
        command.addReference(0, 0);
        command.addQueryPrinterStatus();
        command.addCls();
        command.addText(410, 0, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1, (currentCount + "/" + totalCount));

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(qrImage);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapFactory.decodeStream(fis);

        command.addBitmap(0, 0, LabelCommand.BITMAP_MODE.OVERWRITE, 260, bitmap);
        Vector<Byte> datas = command.getCommand(); // 发送数据
        byte[] bytes = LabelUtils.ByteTo_byte(datas);
        command.addPrint(1, 1);
        printUtils.sendcommand(bytes);
        command.clsCommand();
    }


    @ReactMethod
    public void connect(final String macName) {

        if (macName == null) {
            //ConnectEvent
            WritableMap map = new WritableNativeMap();
            map.putString("code", "0");
            map.putString("error", "macName为空");
            mReactContext
                    .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                    .emit("ConnectEvent", map);
        }

        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    cPrinter.ConnectThreadAddress(macName);
                } catch (
                        Exception e
                        ) {

                    WritableMap map = new WritableNativeMap();
                    map.putString("code", "0");
                    map.putString("error", "连接异常");
                    mReactContext
                            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                            .emit("ConnectEvent", map);

                    Toast.makeText(mReactContext.getApplicationContext(), "连接异常", Toast.LENGTH_SHORT).show();
                }

                StringBuffer sb = new StringBuffer();
                sb.append(cPrinter.stutas());
                String newStr = sb.toString();
                if (newStr.equals("[0]"))

                {
                    Toast("就绪");
                    WritableMap map = new WritableNativeMap();
                    map.putString("code", "0");
                    map.putString("error", "连接");
                    mReactContext
                            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                            .emit("ConnectEvent", map);

                } else if (newStr.equals("[4]"))

                {
                    Toast("缺纸");
                } else if (newStr.equals("[2]"))

                {
                    Toast("标签检测错误");
                } else if (newStr.equals("[8]"))

                {
                    Toast("无碳带");
                } else if (newStr.equals("[16]"))

                {
                    Toast("暂停");
                } else if (newStr.equals("[32]"))

                {
                    Toast("打印中");
                } else if (newStr.equals("[65]"))

                {
                    Toast("开盖有纸");
                } else if (newStr.equals("[69]"))

                {
                    Toast("开盖缺纸");
                } else if (newStr.equals("[128]"))

                {
                    Toast("太热了");
                }
                cPrinter.closeport();
            }
        };
        new Thread() {
            public void run() {
                new Handler(Looper.getMainLooper()).post(runnable);//在子线程中直接去new 一个handler
                //这种情况下，Runnable对象是运行在主线程中的，不可以进行联网操作，但是可以更新UI
            }
        }.start();
    }

    public void Toast(String str) {
        Toast.makeText(getReactApplicationContext(), str, Toast.LENGTH_LONG).show();
    }


    @ReactMethod
    public void close() {
        printUtils.closeport();
    }

    @ReactMethod
    public void openBluetooth() {
        mBtAdapter.enable();
    }

    @ReactMethod
    public void closeBluetooth() {
        mBtAdapter.disable();
    }


    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    WritableMap map = new WritableNativeMap();
                    map.putString("name", device.getName());
                    map.putString("mac", device.getAddress());
                    mReactContext
                            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                            .emit("BluetoothEvent", map);
                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                // setProgressBarIndeterminateVisibility(false);
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = "无蓝牙";
                    mNewDevicesArrayAdapter.add(noDevices);
                }
            }
        }
    };
}

